<?php

namespace Api\Event;


/** 
 * 缓存接口   所有的缓存均在这里进行
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */

class CacheEvent //extends BaseEvent 
{

	public $handler;
	var $prefix = 'IMBA.';

	// protected function _initialize(){
	// 	parent::_initialize();
	// }

	static protected $REDIS_INSTANCE;

	// 获取redis 缓存实例
	static public function instance($db)
	{
		if (empty(self::$REDIS_INSTANCE[$db])){
			self::$REDIS_INSTANCE[$db] = new \Redis;
			self::$REDIS_INSTANCE[$db]->connect(C('REDIS_HOST'));
			C('REDIS_PWD') && self::$REDIS_INSTANCE[$db]->auth(C('REDIS_PWD'));
			self::$REDIS_INSTANCE[$db]->select($db);
		}
		return self::$REDIS_INSTANCE[$db];
	}

	// 获取或设置hash的值
	static public function hashGset($db, $key, $func)
	{
		$instance = self::instance($db);
		$hash = $instance->hgetall($key);
		if (!$hash){
			$hash = $func();
			if ($hash){
				$instance->hmset($key, $hash);
			}
		}
		return $hash;
	}

	static public function remove($db, $key)
	{
		$instance = self::instance($db);
		$instance->delete($key);
	}


	##########################  API ######################

	public function statis($model, $id, $action = 'get', $field = '', $value = null, $expire = '')
	{
		$this->RedisConnect();
		$key = "IMBA.{$model}.statis.{$id}";
		if ($action == 'get')
		{
			if ($field)
			{
				$res = $this->handler->hget($key, $field);
			}
			else
			{
				$res = $this->handler->hgetall($key);
				if ($res)
				{
					unset($res['id'],$res['video_id']);
				}
			}
			return $res;
		}
		elseif ($action == 'set')
		{
			if ($field)
			{

				$this->handler->hset($key, $field, $value);
			}
			else
			{
				$value['id'] = $id;
				$this->handler->hmset($key, $value);
				$expire && $this->handler->expire($key, $expire);
			}
		}
		elseif ($action == 'incr')
		{
			$this->handler->hincrby($key, $field, $value);
		}
	}



	#  DROP
	/** 
	 * 对视频信息进行缓存
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function videoStatis($id, $action = 'get', $field = '', $value = null)
	{
		// return; #关闭缓存
		$this->RedisConnect();
		$key = "IMBA.video.statis.{$id}";
		if ($action == 'get')
		{
			if ($field)
			{
				$res = $this->handler->hget($key, $field);
			}
			else
			{
				$res = $this->handler->hgetall($key);
				if ($res)
				{
					unset($res['id'],$res['video_id']);
				}
			}
			return $res;
		}
		elseif ($action == 'set')
		{
			if ($field)
			{
				$this->handler->hset($key, $field, $value);
			}
			else
			{
				$value['id'] = $id;
				$this->handler->hmset($key, $value);
			}
		}
		elseif ($action == 'incr')
		{
			$this->handler->hincrby($key, $field, $value);
		}
	}

	// 设置搜索一次关键词
	public function setSearchKey($keyword)
	{
		$this->RedisConnect();
		$week = (int)date('YW');
		$key = "IMBA.hotKey.{$week}";
		$res = $this->handler->zincrby($key, 1, $keyword);
	}

	// 获取本周最热门的搜索
	public function getSearchKeyHot($limit = 5)
	{
		$this->RedisConnect();
		$week = (int)date('YW');
		$key = "IMBA.hotKey.{$week}";
		return $this->handler->zrevrange($key, 0, $limit-1);
	}

	

	/** 
	 * 简单缓存 |设置缓存 |  缓存数组或者文字  
	 * @author Legend. <xcx_legender@qq.com>
	 * @param string $key, mixes $data
	 * @return 
	 */
	
	public function set($key, $data = '', $expired = null)
	{
		// return;  #关闭缓存
		$this->RedisConnect();
		$key = $this->prefixKey($key);
		$data = $data ? serialize($data) : null;
		$this->handler->set($key, $data);
		$expired && $this->handler->expire($key, $expired);
		// S($key, $data, $expired);
	}

	/** 
	 * 简单缓存  | 获取缓存 | 缓存数组或者文字
	 * @author Legend. <xcx_legender@qq.com>
	 * @param string $key, mixes $data
	 * @return 
	 */
	public function get($key)
	{
		// return; #关闭缓存
		// $this->Sconnect();
		$this->RedisConnect();
		$key = $this->prefixKey($key);
		$data = $this->handler->get($key);
		$data = $data ? unserialize($data) : '';
		return $data;
	}



	public function del($key)
	{
		$this->RedisConnect();
		$key = $this->prefixKey($key);
		$this->handler->del($key);
	}















	######################  PROTECTED ####################

	protected function Sconnect()
	{
		// 缓存配置
		// S(
		// 	array(
		// 	    'type' => 'redis',
		// 	    'host' => '121.42.11.183',
		// 	    'port' => '6379',
		// 	    'prefix' => 'IMBA.'
		//     )
		// );
	}

	protected function RedisConnect()
	{
		if (!$this->handler)
		{
			$this->handler = new \Redis;
			$this->handler->connect(C('REDIS_HOST'));# todo 使用 api redis - ecs
			C('REDIS_PWD') && $this->handler->auth(C('REDIS_PWD'));
			$this->handler->select(6);
		}
	}

	protected function prefixKey($key)
	{
		return $this->prefix.$key;
	}

	

	# 缓存策略 



	


	/** 
	 * 刷新视频统计缓存 并写入数据库
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	
	public function videoRefresh()
	{
		$this->RedisConnect();
		$items = $this->handler->keys("IMBA.video.statis.*");
		$service = D('Common/Video', 'Service');
		foreach ($items as $key) {
			$ids = explode('.', $key);
			$data = $this->handler->hgetall($key);
			$map['id'] = $video_id = intval($ids[3]);
			unset($data['id']);
			$data = array_map('intval', $data);
			$service->where($map)->setField($data);
			$this->set("video.detail.{$video_id}", null);
			$this->handler->del($key);
		}
	}

}


